package com.example.myapplication.slice;

import com.example.myapplication.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Text;
import ohos.agp.components.webengine.BrowserAgent;
import ohos.agp.components.webengine.Navigator;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;

public class WebAbilitySlice extends AbilitySlice implements Component.ClickedListener {

    private WebView webViewPage;
    private Text tvTitle;
    private String title;
    private Navigator navigator;

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_web);
        initComponent();
        initView(intent);
    }

    private void initComponent() {
        tvTitle = (Text) findComponentById(ResourceTable.Id_tv_title);
        findComponentById(ResourceTable.Id_img_back).setClickedListener(this);
        webViewPage = (WebView) findComponentById(ResourceTable.Id_wb_page);
        webViewPage.setBrowserAgent(new MyBrowserAgent(this));
        navigator = webViewPage.getNavigator();
    }

    private void initView(Intent intent) {
        String url = intent.getStringParam("url");
        title = intent.getStringParam("title");
        tvTitle.setText(title);
        webViewPage.load(url);
    }

    @Override
    public void onClick(Component component) {
        if (navigator.canGoBack()) {
            navigator.goBack();
            return;
        }
        onBackPressed();
    }

    private class MyBrowserAgent extends BrowserAgent {

        public MyBrowserAgent(Context context) {
            super(context);
        }

        @Override
        public void onTitleUpdated(WebView webView, String value) {
            super.onTitleUpdated(webView, value);
            tvTitle.setText(value.isEmpty() ? title : value);
        }

        @Override
        public void onProgressUpdated(WebView webView, int newValue) {
            super.onProgressUpdated(webView, newValue);
        }
    }
}
